package org.swust.monitor.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.swust.monitor.dto.SysUserDto;
import org.swust.monitor.entity.R;
import org.swust.monitor.entity.SysUser;
import org.swust.monitor.entity.qparam.QSysUser;
import org.swust.monitor.service.ISysUserService;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * <p>
 * 系统用户表 前端控制器
 * </p>
 *
 * @author 111
 * @since 2024-12-24
 */
/**
 * 通过ID查询用户信息
 *
 * @return 用户信息
 */
@RestController
@RequestMapping("/user")

public class SysUserController {
    @Autowired
    private ISysUserService userService;
    /**
     * 通过ID查询用户信息
     *
     * @param id ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    public R<Serializable> user(@PathVariable Integer id) {
        return R.ok(userService.getById(id));
    }
    /**
     * 添加用户
     *
     * @param user 用户信息
     * @return success/false
     */
    @PostMapping
    public R<Integer> saveUser(@RequestBody SysUser user) {
        user.setUpdateTime(LocalDateTime.now());
        userService.save(user);
        return R.ok(user.getUserId());
    }
    /**
     * 更新用户信息
     *
     * @param user 用户信息
     * @return R
     */

    @PutMapping
    public R<Integer> updateUser(@Valid @RequestBody SysUser user) {
        userService.updateById(user);
        return R.ok(user.getUserId());
    }

    /**
     * 删除用户信息
     *
     * @param id ID
     * @return R
     */

    @DeleteMapping("/{id}")
    public R<Boolean> delUser(@PathVariable Integer id) {
        return R.ok(userService.removeById(id));
    }
    /**
     * 分页查询用户
     *
     * @param page    参数集
     * @param qSysUser 查询参数列表
     * @return 用户集合
     */
    @GetMapping("/page")
    public R<IPage<SysUserDto>> getUserPage(Page page, QSysUser qSysUser) {
        return R.ok(userService.pageUser(page, qSysUser));
    }

    /**
     * 修改密码并删除token
     * @param userId
     * @return
     */
    @PutMapping("/resetPwd")
    public R resetPwd(Integer userId) {

        Boolean result = userService.resetPwd(userId);
        if(result){
            return R.ok("密码修改成功");
        }else{
            return R.failed("原始密码输入错误，修改失败！");
        }

    }

    @GetMapping("/list")
    public R userList() {
        return R.ok(userService.list());
    }
}
